package com.example.patentback.service.impl;

import com.example.patentback.dao.SysRoleMenuMapper;
import com.example.patentback.entity.SysRole;
import com.example.patentback.entity.SysRoleMenu;
import com.example.patentback.service.SysRoleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class SysRoleMenuServiceImpl implements SysRoleMenuService {

    @Autowired
    SysRoleMenuMapper sysRoleMenuMapper;

    @Override
    public int deleteRoleMenuByMenuId(Long id) {
        Example example = new Example(SysRoleMenu.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("menuId", id);
        return sysRoleMenuMapper.deleteByExample(example);
    }

    @Override
    public List<SysRoleMenu> selectRoleMenuByRoleId(Long id) {
        Example example = new Example(SysRoleMenu.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("roleId", id);
        return sysRoleMenuMapper.selectByExample(example);
    }

    @Override
    public int deleteRoleMenuByRoleId(Long[] ids) {
        Example example = new Example(SysRoleMenu.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("roleId", Arrays.asList(ids));
        return sysRoleMenuMapper.deleteByExample(example);
    }

    @Override
    public int updateRoleMenu(Long roleId, Long[] menuIds) {
        List<SysRoleMenu> sysRoleMenus = new ArrayList<>();
        Arrays.stream(menuIds).forEach(menuId -> {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRoleId(roleId);
            sysRoleMenu.setMenuId(menuId);
            sysRoleMenus.add(sysRoleMenu);
        });
        //先删除原来的关联
        Example example = new Example(SysRoleMenu.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("roleId", roleId);
        sysRoleMenuMapper.deleteByExample(example);
        //插入新分配的菜单权限
        return sysRoleMenuMapper.insertList(sysRoleMenus);
    }
}
